package com.igame.Service.impl;

import com.google.gson.Gson;
import com.igame.Service.CommentService;
import com.igame.common.Result;
import com.igame.constant.CommentConstant;
import com.igame.entity.Comment;
import com.igame.mapper.CommentMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
public class CommentImpl implements CommentService {

    @Autowired
    CommentMapper commentMapper;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Override
    public Result<List<Comment>> getComment(Integer id) {
        String cacheKey = "comments:" + id;
        String cachedComments = stringRedisTemplate.opsForValue().get(cacheKey);

        if (cachedComments != null) {
            // 缓存命中
            List<Comment> comments = deserializeComments(cachedComments);
            return Result.success(comments);
        } else {
            // 缓存未命中，从数据库获取数据
            List<Comment> comments = commentMapper.getAllParentComments(id);
            // 将数据存入 Redis 缓存
            stringRedisTemplate.opsForValue().set(cacheKey, serializeComments(comments), 1, TimeUnit.HOURS);
            return Result.success(comments);
        }
    }

    @Override
    @Transactional
    public Result insertComment(Comment comment) {

        Result result = new Result();
        try {
            String content = comment.getContent();
            int colonIndex = content.indexOf(':');
            String repComment = content.substring(colonIndex + 1);
            if (content == null || content.trim().isEmpty() || repComment == null || repComment.trim().isEmpty()) {
                throw new RuntimeException("发送内容不能为空!");
            }
            comment.setIsNew(CommentConstant.isNew);
            commentMapper.insertComment(comment);
            result.setState(true);
            result.setErrMessage(null);
            // 清除缓存
            clearCache(comment.getGoodsId());
        } catch (Exception e) {
            // 发生异常时回滚事务
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            result.setState(false);
            result.setErrMessage(e.getMessage());
        }
        return result;
    }
    @Override
    public void clearCache(Integer goodsId) {
        String cacheKey = "comments:" + goodsId;
        stringRedisTemplate.delete(cacheKey);
    }

    @Override
    public Result<List<Comment>> getReply(String userName) {
        return Result.success(commentMapper.getReply(userName.replace("\"", "")));
    }

    // 序列化评论为 JSON 字符串
    private String serializeComments(List<Comment> comments) {
        return new Gson().toJson(comments);
    }
    // 解析 JSON 字符串为评论列表
    private List<Comment> deserializeComments(String json) {
        Comment[] commentsArray = new Gson().fromJson(json, Comment[].class);
        return List.of(commentsArray);
    }
}
